<script lang="ts" setup>
defineOptions({
  name: "VueVideo"
});
import { YoutubeIframe } from "@vue-youtube/component";
import { LocalStorage } from "@/assets/js/storage.ts";

const emit = defineEmits(["ready", "ended", "update:options"]);
const props = defineProps({
  options: {
    type: [Object],
    default: () => ({})
  }
});
const youtubeIframeRef = ref(null);
const videoRef: any = ref(null);
const { options } = props;
const mute = ref<0 | 1>(0);

onBeforeMount(() => {
  mute.value = +LocalStorage.getItem("mute") as 1 | 0;
});
onMounted(() => {
  emit("ready", youtubeIframeRef.value);
});

const innerStyle = {
  width: "100%",
  height: "100%"
};
const youtubePlayer = ref<any>(null);

const onReady = (event: { target: any }) => {
  youtubePlayer.value = event.target;
  console.log("🚀 ~ event.target:", event.target);
  observerVideoItems.observe(videoRef.value);
};

let observerVideoItems = new IntersectionObserver(
  entries => {
    entries.forEach(async (entry: any) => {
      if (entry.isIntersecting === true) {
        unref(youtubePlayer).playVideo();
      } else {
        unref(youtubePlayer).pauseVideo();
      }
    });
  },
  { threshold: 0.75 }
);

onBeforeUnmount(() => {
  observerVideoItems.unobserve(videoRef.value);
});
</script>
<template>
  <div data-vjs-player :style="innerStyle" ref="videoRef">
    <YoutubeIframe
      ref="youtubeIframeRef"
      :playerVars="{
        autoplay: 0,
        mute,
        loop: 1,
        playlist: options.youtubeId,
        rel: 0, // 避免播放结束后显示相关视频
        modestbranding: 1, // 减少 YouTube 徽标显示
        controls: 1, // 隐藏播放控件
        showinfo: 0,
        iv_load_policy: 3
      }"
      :video-id="options.youtubeId"
      @ready="onReady"
      width="100%"
      height="100%"
    />
  </div>
</template>
